chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log("[MESSAGE] " + (sender.tab ? "from a content script:" + sender.tab.url : "from the extension"));
        if (request) {
            console.log("[INFO] " + JSON.stringify(request));
            let fileName = createFile(request);
            console.log("生成文件: %s", fileName);
            sendResponse(`文件已生成: ${fileName}`);
        }
    }
);

function createFile(str) {
    str = JSON.stringify(JSON.parse(str), null, 2)  // 美化JSON，添加缩进
    let blob = new Blob([str], { type: 'application/json' });
    let url = URL.createObjectURL(blob);
    let now = new Date();
    let fileName = `${now.getTime()}.json`;
    console.log('Download Link: %o', url)

    // chrome.downloads.download({ // 然而 conent_script 无法直接调用 downloads 接口
    //     url: url,
    //     filename: fileName
    // })

    download(url, fileName);

    return fileName;
}

function download(url, fileName) {
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    a.href = url;
    if (fileName) a.download = fileName;
    a.click();
    a.remove();
}